Skip to content

feat: add runtime opt-out for capture - #1047

Draft
posthog[bot] wants to merge 1 commit into
mainfrom
posthog/python-opt-out-capturing
Draft

posthog[bot] wants to merge 1 commit into
mainfrom
posthog/python-opt-out-capturing

Conversation

@posthog

@posthog posthog Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Why: This came out of the cross-SDK compliance matrix in PostHog/sdk-specs — posthog-python is marked 🟡 Partial on the Capture contract because it has no runtime opt-out.

The capture spec requires an opt-out short-circuit:

Disabled/opt-out short-circuit. If the SDK has been disabled (disabled=true) or the user/process has opted out (opt_out=true), the call returns immediately with no event emitted. Opt-out state is usually persisted client-side and in-memory server-side.

The acceptance scenario Capture honors opt-out state (acceptance/public/capture.feature) is tagged @both, so it applies to server SDKs too.

The matrix note (compliance/posthog-python.md, n4 — Capture):

There is still no dynamic, runtime-toggleable opt-out API. The only short-circuit is the constructor-time disabled flag — a static kill-switch set once at construction, not the dynamic per-call opt_out_capturing()/is_opted_out() API pair other server SDKs (e.g. posthog-node) expose.

Backwards compatibility: Backward-compatible — adding opt_in()/opt_out()/is_opted_out() methods that toggle a new or existing internal flag is purely additive.

What changed

  • New Client.opt_out_capturing(), Client.opt_in_capturing() and Client.is_opted_out(), plus the matching module-level helpers on the global client.
  • The gate lives in Client._enqueue, which every event-producing API (capture, capture_ai, capture_exception, set, set_once, group_identify, alias) already funnels through — so one check covers them all, and events are dropped before anything is queued or sent.
  • Feature flag evaluation and other non-capture APIs are deliberately unaffected, matching the *_capturing naming and the browser SDK's opt_in_capturing() / opt_out_capturing() surface.

Backwards compatibility

Purely additive. Three new methods, no signature or behavior change for any existing caller — a client that never calls opt_out_capturing() behaves exactly as before. The state is independent of the constructor-time disabled kill switch: opt_in_capturing() does not re-enable a client constructed with disabled=True (covered by a test).

Note the state is in-memory per client and does not survive a process restart, which is what the spec describes for server SDKs ("in-memory server-side"). Applications that need it to persist should store the user's choice themselves and re-apply it at startup; this is documented on the methods.

💚 How did you test it?

  • New unit tests in posthog/test/test_client.py: events dropped with no network request while opted out (across capture/set/alias/group_identify), capture resumes after opt_in_capturing(), opt_in_capturing() does not revive a disabled=True client, and feature flags keep working while opted out.
  • New module-level test in posthog/test/test_module.py covering the global-client helpers.
  • Full CI-aligned checks run locally: ruff format --check ., ruff check ., mypy ... | mypy-baseline filter (clean), python -W error -c "import posthog", make public_api_check, and the full pytest suite — 4545 passed. The only 8 failures are pre-existing AI integration tests (posthog/test/ai/openai, anthropic, langchain) that need live provider credentials; they are untouched by this change.
  • references/public_api_snapshot.txt regenerated via make public_api_snapshot (3 new functions, 3 new methods).

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Fully autonomous

Produced by a scheduled agent run that reads the compliance matrices in PostHog/sdk-specs, ranks the open 🟡/❌ cells, and implements one backward-compatible gap per run. Tooling: Claude Code with shell, GitHub CLI and the repo's own make/uv checks.

Decisions along the way: several higher-ranked candidates were dropped after checking the actual repos — the .NET malformed-payload gap and the Ruby FeatureFlagEvaluations#enabled? default-value gap are already fixed on their main branches (the matrix notes are stale), and the posthog-js exception-metadata and posthog-go MCP exception gaps already have work in flight. Within this change, the gate was placed in _enqueue rather than in each public capture method so no path can be missed, and the scope was kept to capture only (flags untouched) to match the spec's wording and the *_capturing naming.

Follow-up work

  • The matrix's other open Capture-adjacent items for this SDK are out of scope here and unchanged.
  • The opt-in / is-opt-out specs are currently scoped client; if the server-side half of this behavior should be specified too, that is a change for sdk-specs, not this repo.

Created with PostHog Desktop

🤖 Generated with Claude Code

The capture contract requires an opt-out state that drops events silently
with no network request, but the SDK only had the constructor-time
`disabled` kill switch, which cannot be toggled at runtime.

Add `opt_out_capturing()`, `opt_in_capturing()` and `is_opted_out()` on
`Client` (and the matching module-level helpers). The gate lives in
`_enqueue`, so every event-producing API short-circuits while opted out.
Feature flag evaluation and other non-capture APIs are unaffected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: da91345a-57f0-47dd-a7ae-1f0a25bbc6fd
@github-actions

github-actions Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-10T06:15:57.636143+00:00
Duration: 259846ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 516ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 512ms
Required Headers.Has Authorization Bearer Header ✅ 511ms
Required Headers.Has Content Type Json ✅ 512ms
Required Headers.Has Posthog Sdk Info Format ✅ 511ms
Required Headers.Has Posthog Attempt Header ✅ 511ms
Required Headers.Has Posthog Request Id ✅ 511ms
Required Headers.Has Posthog Request Timestamp ✅ 511ms
Required Headers.Has User Agent ✅ 511ms
Body Format.Body Has Created At And Batch ✅ 511ms
Body Format.No Api Key In Body ✅ 511ms
Body Format.No Sent At In Body ✅ 510ms
Event Format.Event Has Required Root Fields ✅ 511ms
Event Format.Event Uuid Is Valid ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 ✅ 511ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 516ms
Event Format.Distinct Id Is String ✅ 511ms
Event Format.Distinct Id At Root Not Properties ✅ 511ms
Event Format.Custom Properties Preserved ✅ 511ms
Event Format.Set Properties Preserved ✅ 511ms
Event Format.Set Once Properties Preserved ✅ 510ms
Event Format.Groups Properties Preserved ✅ 511ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 511ms
Event Format.Event Has Required Root Fields Batch ✅ 515ms
Event Format.Event Uuid Is Valid Batch ✅ 514ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 513ms
Event Format.Custom Properties Preserved Batch ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 515ms
Event Format.Set Once Properties Preserved Batch ✅ 513ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 514ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 516ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 507ms
Batch Behavior.Flush At Triggers Batch ✅ 1012ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 511ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 513ms
Deduplication.Preserves Uuid On Retry ✅ 6521ms
Deduplication.Preserves Timestamp On Retry ✅ 6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6524ms
Deduplication.No Duplicate Events In Batch ✅ 519ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13525ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6520ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 512ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 514ms
Response Format Validation.Success No Retry After When All Ok ✅ 514ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 513ms
Response Format Validation.Response Echoes Request Id ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6520ms
Retry Behavior.Retries On 500 ✅ 6520ms
Retry Behavior.Retries On 503 ✅ 8524ms
Retry Behavior.Retries On 504 ✅ 6520ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11521ms
Retry Behavior.Does Not Retry On 400 ✅ 2514ms
Retry Behavior.Does Not Retry On 401 ✅ 2515ms
Retry Behavior.Does Not Retry On 402 ✅ 2514ms
Retry Behavior.Does Not Retry On 413 ✅ 2514ms
Retry Behavior.Does Not Retry On 415 ✅ 2515ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2513ms
Retry Behavior.Implements Backoff ✅ 22537ms
Retry Behavior.Max Retries Respected ✅ 22523ms
Partial Batch Handling.Handles 200 Full Success ✅ 2514ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3517ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3515ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3517ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6521ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6521ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6522ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6522ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6521ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3520ms
Compression.Sends Gzip Content Encoding ✅ 510ms
Compression.No Content Encoding When Disabled ✅ 511ms
Compression.Compressed Body Is Decompressible ✅ 510ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2512ms
Event Options.Cookieless Mode Override ✅ 511ms
Event Options.Disable Skew Correction Override ✅ 511ms
Event Options.Process Person Profile Override ✅ 510ms
Event Options.Product Tour Id Override ✅ 512ms
Event Options.Unset Options Omitted ✅ 510ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 511ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 511ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 511ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 511ms
Identity.Capture Ai Event Has Uuid ✅ 511ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 510ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 511ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 12ms
Request Payload.Flags Request Uses V2 Query Param ✅ 9ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 8ms
Request Payload.Flags Request Omits Authorization Header ✅ 9ms
Request Payload.Token In Flags Body Matches Init ✅ 8ms
Request Payload.Groups Round Trip ✅ 8ms
Request Payload.Groups Default To Empty Object ✅ 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 8ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 8ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 9ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 508ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 9ms
Retry Behavior.Retries Flags On 502 ✅ 314ms
Retry Behavior.Retries Flags On 504 ✅ 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 512ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 65ms
Versioned Boolean Matching.Matching Version 1 ✅ 62ms
Versioned Boolean Matching.Matching Version 2 ✅ 60ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 32ms

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants